﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Reviewer {
    public partial class FrmGameLists : Form {
        private FrmMain frmMain;
        private DBHelper dbHelper = new DBHelper();
        private DataTable listSource;

        public FrmGameLists(FrmMain frmMain) {
            InitializeComponent();
            this.Icon = Icon.FromHandle(Properties.Resources.table.GetHicon());
            this.frmMain = frmMain;
        }

        public void LoadGameList(string pid, string move, string gameType, string result) {
            listSource = dbHelper.GetListGames(pid, move, gameType, result);
            FilterGames();
            this.Text = "Games List (" + lbxGames.Items.Count.ToString() + " games)"; 
        }

        public void LoadGameList(string pid, string gameType, string result) {
            listSource = dbHelper.GetListGames(pid, gameType, result);
            FilterGames();
            this.Text = "Games List (" + lbxGames.Items.Count.ToString() + " games)";
        }

        private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e) {
            if(lbxGames.SelectedIndex >= 0) {
                DataTable dt = dbHelper.GetGameInfo(lbxGames.SelectedValue.ToString());
                if(dt.Rows.Count == 1) {
                    StringBuilder hgn = new StringBuilder();
                    hgn.Append(dt.Rows[0]["BSID"].ToString() + " ");
                    hgn.Append(dt.Rows[0]["GameType"].ToString() + " ");
                    hgn.Append(dt.Rows[0]["WhitePlayer"].ToString() + " ");
                    hgn.Append(dt.Rows[0]["BlackPlayer"].ToString() + " ");
                    hgn.Append(dt.Rows[0]["GameResult"].ToString() + " ");
                    hgn.Append(dt.Rows[0]["WhiteTime"].ToString() + " ");
                    hgn.Append(dt.Rows[0]["BlackTime"].ToString() + " ");
                    hgn.Append(dt.Rows[0]["Moves"].ToString());

                    frmMain.LoadDecodedHGNX(hgn.ToString());
                }
            }
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e) {
            if(e.KeyCode == Keys.Enter) {
                FilterGames();
                return;
            }
        }

        private void FilterGames() {
            string keyword = tbxKeyword.Text.Trim();            
            List<string> list = new List<string>();
            string bsid;
            for(int i = 0; i < listSource.Rows.Count; i++) {
                bsid = listSource.Rows[i]["BSID"].ToString();
                if(keyword == "" || bsid.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) > -1) {
                    list.Add(bsid);
                }
            }
            lbxGames.DataSource = list;
        }
    }
}
